﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ShellExplosion1 : MonoBehaviour
{
    public LayerMask m_TargetMask;
    public float m_MaxDamage = 100f;
    public float m_Radius = 5f;
    public float m_MaxForce = 1000f;
    public float m_MaxLifeTime = 2f;
    public AudioSource m_ExplosionAudio;
    public ParticleSystem m_ExplosionParticle;

    private void Start()
    {
        Destroy(gameObject,m_MaxLifeTime);
    }

    private void OnTriggerEnter(Collider other)
    {
        Collider[] colliders = Physics.OverlapSphere(transform.position, m_Radius, m_TargetMask);
        for (int i = 0; i < colliders.Length; i++)
        {
            Rigidbody rb = colliders[i].GetComponent<Rigidbody>();
            if(!rb)
            {
                continue;
            }


            rb.AddExplosionForce(m_MaxForce,transform.position,m_Radius);

            TankHealth1 targetHealth = rb.GetComponent<TankHealth1>();
            if (!targetHealth)
                continue;

            float damage = CalculateDamage(other.transform.position);
            targetHealth.TakeDamage(damage);
        }

        m_ExplosionParticle.transform.parent = null;
        m_ExplosionParticle.Play();
        m_ExplosionAudio.Play();

        Destroy(m_ExplosionParticle.gameObject, m_ExplosionParticle.main.duration);
        Destroy(gameObject);

    }

    float CalculateDamage(Vector3 targetPos)
    {
        float damage = 0;
        Vector3 targetToShell = targetPos - transform.position; ;
        float distance = targetToShell.magnitude;
        damage = m_MaxDamage * ((m_Radius - distance )/ m_Radius);
        damage = Mathf.Max(0f, damage);

        return damage;
    }
}

